import React from 'react'
import { Upload, Button, message, Modal, Divider, Progress } from 'antd'
import { PlusCircleFilled, PictureTwoTone, FilePdfTwoTone } from '@ant-design/icons'
import { uploadFile, luanchTask, getTaskStatus, getDownloadUrl } from '@utils/api'
import { getBase64, checkType } from '@utils/upload'
const { Dragger } = Upload

// JPG上传组件，允许多个文件上传
function JpgUpload({ type, fetchCount }) {
  const initialState = {
    fileList: [],
    targetId: '',
    process: '未上传',
    percent: 5,
    startConvert: false,
    previewTitle: '',
    previewVisible: false,
    previewImage: '',
  }

  const [state, dispatch] = React.useReducer((state, action) => {
    console.log('action', action)
    switch (action.type) {
      // 重新赋值
      case 'clear':
        return initialState
      default:
        const newState = Object.assign({}, state, action.payload)
        return newState
    }
  }, initialState)

  const { fileList, targetId, process, percent, startConvert, previewTitle, previewVisible, previewImage } = state

  // 预览事件处理
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }
    dispatch({
      payload: {
        previewImage: file.url || file.preview,
        previewVisible: true,
        previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
      },
    })
  }

  // 图片上传值改变事件
  const handleChange = (change) => {
    const { file, fileList } = change
    // 校验文件类型
    if (checkType(file, type)) {
      message.error(`文件类型错误，请重新上传格式为 ${type.accept} 的文件！`)
      dispatch({ payload: { fileList: [] } })
      // setFileList([])
      return
    }

    // 否则允许上传成功
    const newFileList = fileList.map((element) => {
      if (element.status !== 'removed') {
        return { ...element, status: 'done' }
      }
      return null
    })
    // setFileList(newFileList)
    dispatch({ payload: { fileList: newFileList } })
  }

  // 处理退出预览事件
  const handleCancel = () => {
    dispatch({ payload: { previewVisible: false } })
  }

  // 图片上传按钮
  const uploadButton = (
    <div>
      <PlusCircleFilled style={{ fontSize: 48, color: '#ff9b69' }} />
    </div>
  )

  // 自定义上传
  const handleCustomRequest = (options) => {
    // const { onSuccess, onError, file, onProgress } = options
  }

  // 上传前的事件，有点坑，无法阻止数据到文件列表
  const handleBeforeUpload = (file, fileList) => {}

  // 处理转换
  const handleConvert = async () => {
    // 先校验次数
    const overCount = await fetchCount(true)
    if (overCount) {
      return
    }

    dispatch({
      payload: {
        startConvert: true,
        process: '开始上传',
        percent: 10,
      },
    })

    // 构建多文件表单
    let formData = new FormData()
    fileList.forEach((file) => {
      formData.append('file', file.originFileObj)
    })

    // 调用上传文件接口
    const { target } = await uploadFile(formData)

    if (target) {
      dispatch({
        payload: {
          targetId: target,
          process: '已上传',
          percent: 30,
        },
      })
    }

    // 开始转换参数
    const param = {
      convertType: type.exportType,
      target: target,
    }

    // 调用开始转换接口
    const data = await luanchTask(param)
    if (!data) {
      return dispatch({
        payload: {
          process: '开始转换失败',
        },
      })
    }

    dispatch({
      payload: {
        process: '开始转换',
        percent: 40,
      },
    })
    const { status, code, message: msg } = data
    if (status === true) {
      if (code === -1) {
        // 转换失败
        dispatch({
          payload: {
            process: '转换失败',
          },
        })
        return
      } else if (code === 0) {
        // 转换未开始：这种情况继续查询
        dispatch({
          payload: {
            process: '转换未开始',
          },
        })
      } else if (code === 1) {
        // 转换中：这种情况继续查询
        dispatch({
          payload: {
            process: '转换中',
          },
        })
      } else if (code === 2) {
        // 转换成功
        dispatch({
          payload: {
            process: '转换完成',
          },
        })
      } else if (code === 4) {
        // 超出IP限制
        message.error(msg)
        dispatch({
          payload: {
            process: '转换失败',
          },
        })
        return
      }
    } else if (status === false) {
      // 请求失败
      message.error(msg)
      dispatch({
        payload: {
          process: '请求失败',
        },
      })
      return
    }

    // 查询状态
    queryConvertResult(target)
  }

  const queryConvertResult = async (target) => {
    // 开始转换参数
    const param = {
      convertType: type.exportType,
      target: target,
    }
    // 查询转换结果
    const intervalFetch = setInterval(async () => {
      // 调用状态查询接口
      let data
      try {
        data = await getTaskStatus(param)
      } catch (e) {
        clearInterval(intervalFetch)
      }

      if (!data) {
        dispatch({
          payload: {
            process: '查询状态失败',
          },
        })
        clearInterval(intervalFetch)
        return
      }

      const { status, code, message: msg } = data
      if (status === true) {
        if (code === -1) {
          // 转换失败
          dispatch({
            payload: {
              process: '转换失败',
            },
          })
          clearInterval(intervalFetch)
        } else if (code === 0) {
          // 转换未开始：这种情况继续查询
          dispatch({
            payload: {
              process: '转换未开始',
            },
          })
        } else if (code === 1) {
          // 转换中：这种情况继续查询
          dispatch({
            payload: {
              process: '转换中',
              percent: 70,
            },
          })
        } else if (code === 2) {
          // 转换成功：关闭循环定时器
          message.success('转换完成')
          dispatch({
            payload: {
              process: '转换完成',
              percent: 100,
            },
          })
          clearInterval(intervalFetch)
        } else if (code === 4) {
          // 超出IP限制
          message.error(msg)
          dispatch({
            payload: {
              process: '转换失败',
            },
          })
          clearInterval(intervalFetch)
        }
      } else if (status === false) {
        // 请求失败
        message.error(msg)
        dispatch({
          payload: {
            process: '请求失败',
          },
        })
        clearInterval(intervalFetch)
      }
    }, 1000)
  }

  // 重新开始
  const handleRestart = () => {
    dispatch({ type: 'clear' })
  }

  return (
    <div className='img-upload-out'>
      {!startConvert && (
        <>
          <div id='file-upload' style={{ display: fileList.length < 1 ? 'block' : 'none' }}>
            <span>
              <Dragger
                name={'file'}
                multiple={true}
                accept={type.accept}
                showUploadList={false}
                customRequest={() => {}}
                onChange={(change) => handleChange(change)}
                maxCount={10}
                fileList={fileList}
                beforeUpload={(file, fileList) => {
                  handleBeforeUpload(file, fileList)
                }}
              >
                <p className='ant-upload-drag-icon'>
                  <PlusCircleFilled className='pluscircle-icon' />
                </p>
                <p className='ant-upload-text'>选择文件</p>
              </Dragger>
            </span>
          </div>
          <div className='img-upload-inner' style={{ display: fileList.length >= 1 ? 'block' : 'none' }}>
            <Upload
              listType='picture-card'
              fileList={fileList}
              onPreview={(file) => handlePreview(file)}
              onChange={(change) => handleChange(change)}
              accept={type.accept}
              customRequest={(options) => handleCustomRequest(options)}
              maxCount={10}
              multiple
              beforeUpload={(file, fileList) => {
                handleBeforeUpload(file, fileList)
              }}
            >
              {fileList.length >= 10 ? null : uploadButton}
            </Upload>
            <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={() => handleCancel()}>
              <img alt='example' style={{ width: '100%' }} src={previewImage} />
            </Modal>
            <Divider />
            <div className={'img-upload-Button'}>
              <Button className='transform-button' type='primary' onClick={() => handleConvert()}>
                开始转换
              </Button>
            </div>
          </div>
        </>
      )}
      {startConvert && (
        <>
          <div className='conver-img-content'>
            <PictureTwoTone twoToneColor='#F6742D' style={{ fontSize: 30 }} />
            <img
              src=''
              alt='converIcon'
              className='convert-icon'
            ></img>
            <FilePdfTwoTone twoToneColor='#F6742D' style={{ fontSize: 30 }} />
          </div>
          <Progress
            className='jpg-convert-prog'
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
            percent={percent}
            status={process.indexOf('失败') === -1 ? 'normal' : 'exception'}
          ></Progress>
          <p className='jpg-convert-des'>{process}</p>
          {process === '转换完成' && (
            <div className={'img-convert-button'}>
              <Button
                className='transform-button'
                type='primary'
                onClick={() => handleRestart()}
                style={{ marginRight: 30 }}
              >
                重新开始
              </Button>

              <Button className='transform-button' type='primary'>
                <a href={getDownloadUrl(targetId)}>立即下载</a>
              </Button>
            </div>
          )}
        </>
      )}
    </div>
  )
}

export default JpgUpload
